package beans.taskprocess;

class TaskRunner implements Runnable
{
	public static final int STATUS_IDLE = -2;
	public static final int STATUS_STARTING = -1;
	public static final int STATUS_RUNNING = 0;
	public static final int STATUS_STOPED = 1;
	public static final int STATUS_KILLED = 2;

	private TaskNode __taskNode;
	private Thread __thread;
	private int __status;

	TaskRunner()
	{
		__status = STATUS_IDLE;
	}

	public void run()
	{
		__thread = Thread.currentThread();
		while (true)
		{
			try
			{
				System.out.println("sleep: " + __thread.getName());
				__status = STATUS_IDLE;
				Thread.sleep(Long.MAX_VALUE);
				continue;
			}
			catch (InterruptedException exception)
			{
				if (__status == STATUS_KILLED)
					continue;
				System.out.println("wake up: " + __thread.getName());
			}
			catch (RuntimeException exception)
			{
				System.out.println("some stupid error ocurs: " + __thread.getName() + ' ' + exception.toString());
			}
			if ((__taskNode != null) && (__status == STATUS_IDLE))
				try
				{
					__status = STATUS_RUNNING;
					__taskNode.doTask();
				}
				catch (RuntimeException exception)
				{
					// ignore?
				}
				finally
				{
					__taskNode = null;
				}
			else
			{
				__status = STATUS_STOPED;
				System.out.println("stop: " + Thread.currentThread().getName());
				break;
			}
		}
		__status = STATUS_STOPED;
	}

	void doTask(TaskNode task)
	{
		if (task == null)
			throw new IllegalArgumentException("task = null");
		if (__status != STATUS_IDLE)
			throw new IllegalStateException("Not idle!!");
		__taskNode = task;
		__status = STATUS_STARTING;
		__thread.interrupt();
	}

	void killIfNeed()
	{
		if ((__status == STATUS_RUNNING) && (__taskNode != null) && __taskNode.isTimeouted())
		{
			// __status=STATUS_KILLED;
			// kill( );
		}
	}

	void kill()
	{
		__thread.interrupt();
	}

	int status()
	{
		return __status;
	}

	@Override
	public String toString()
	{
		return __thread.toString();
	}
}
